/**
 * @description 校验规则组件
 */
import { Component, Emit, Prop, Watch } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'

import { getKeyToEnum, ValidRuleTypeCnEnum } from '@/const/enum'
import type { OptionDto } from '@/components/low-code/types'
import { numberToLetter } from '@/utils/util'
import { Button, Input, Select, Timeline, TimelineItem, TimePicker } from 'ant-design-vue'
import { CloseOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { h } from 'vue'

export interface ValidRuleDto {
    type: number
    time: string
    clock?: string
    limit: number
    min: number
    max: number
}

export interface ValidRuleItemDto extends ValidRuleDto {
    typeOptions: OptionDto[]
}

@Component
export class ValidRule extends Render {
    ruleList = [] as ValidRuleItemDto[]

    options = getKeyToEnum(ValidRuleTypeCnEnum)

    @Emit('update:modelValue')
    handleEmitUpdate(val: ValidRuleDto[]) {
        return val
    }

    @Watch('modelValue', { deep: true, immediate: true })
    handleWatchValiateRuleData(val: ValidRuleItemDto[]) {
        this.ruleList = val || []
        // 没有值时默认添加一条
        if (!this.ruleList.length) {
            this.ruleList.push(this.createRuleData())
            this.handleEmitUpdate(this.ruleList)
        }
    }

    // 创建规则，过滤生效方式及其默认值
    createRuleData() {
        const options = this.getOption()
        const defaultType = options[0].value as number
        return {
            type: defaultType,
            typeOptions: options,
            time: '',
            clock: '',
            limit: 1,
            min: 0,
            max: 0
        }
    }

    getOption() {
        const typesValue = this.ruleList.map((i) => i.type)
        const options = this.options.filter((i) => !typesValue.includes(i.value as number))
        return options
    }

    onAddRule() {
        const rule = this.createRuleData()
        this.ruleList.push(rule)
        this.handleRefreshOption(rule, 'add')
    }

    onRemove(ruleData: ValidRuleItemDto, index: number) {
        this.ruleList.splice(index, 1)
        this.handleRefreshOption(ruleData, 'remove')
    }

    // 新增或删除时，刷新其他规则的生效方式的options
    handleRefreshOption(curRule: ValidRuleItemDto, type: string) {
        switch (type) {
        case 'add':
            // 新增时要在已存在的规则中把新生成的一条的生效方式从options中移除
            this.ruleList.forEach((item, idx) => {
                if (idx !== this.ruleList.length - 1) {
                    const index = item.typeOptions?.findIndex((i) => i.value === curRule.type)
                    if (index !== -1) {
                        item.typeOptions?.splice(index as number, 1)
                    }
                }
            })
            break
        case 'remove':
            // 移除时要在已存在的规则中把删除的生效方式从options中加回去
            this.ruleList.forEach((item) => {
                item.typeOptions?.push(...curRule.typeOptions)
            })
        }
    }

    renderRule(ruleData: ValidRuleItemDto, index: number) {
        return (
            <div class="leading-10">
                <div class="flex items-center">
                    <div>
                        <span>生效方式等于</span>
                        <Select v-model={ruleData.type} class="!w-120px px-5px">
                            {/* {ruleData?.typeOptions?.map((item) => (
                                <ElOption
                                    label={item.label}
                                    value={item.value as number}
                                ></ElOption>
                            ))} */}
                        </Select>
                        <span>时；</span>
                        {this.renderRuleDetail(ruleData)}
                    </div>
                    <div>
                        {this.ruleList.length !== 1 && (
                            <div
                                class="cursor-pointer"
                                onClick={() => this.onRemove(ruleData, index)}
                            >
                                <CloseOutlined />
                            </div>
                        )}
                    </div>
                </div>
            </div>
        )
    }

    renderRuleDetail(ruleData: ValidRuleItemDto) {
        switch (ruleData.type) {
        case ValidRuleTypeCnEnum.次日生效:
            return (
                <>
                    <span>每日</span>
                    <TimePicker
                        v-model={ruleData.time}
                        class="!w-100px px-5px"
                    ></TimePicker>
                    <span>操作加保，生效时间可以选择次日；人数限制</span>
                    <Select class="!w-100px px-5px" v-model={ruleData.limit} disabled>
                        {/* <ElOption label="普通" value={1}></ElOption> */}
                    </Select>
                    <span>规则，起投人数≥</span>
                    <Input v-model:value={ruleData.min} class="!w-100px px-5px"></Input>
                    <span>人，且在保人数≥</span>
                    <Input v-model:value={ruleData.max} class="!w-100px px-5px"></Input>
                    <span>人</span>
                </>
            )
        case ValidRuleTypeCnEnum.整点生效:
            return (
                <>
                    <span>，第一次激活保单，生效时间只能选择次日；每日</span>
                    <TimePicker
                        v-model={ruleData.time}
                        class="!w-100px px-5px"
                    ></TimePicker>
                    <span>之前，每一个整点</span>
                    <TimePicker
                        v-model={ruleData.clock}
                        class="!w-100px px-5px"
                    ></TimePicker>
                    <span>之前操作加保，次整点生效；人数限制</span>
                    <Select v-model={ruleData.limit} class="!w-100px px-5px" disabled>
                        {/* <ElOption label="普通" value={1}></ElOption> */}
                    </Select>
                    <span>规则，起头人数≥</span>
                    <Input v-model={ruleData.min} class="!w-100px px-5px"></Input>
                    <span>人，且在保人数≥</span>
                    <Input v-model={ruleData.min} class="!w-100px px-5px"></Input>
                    <span>人</span>
                </>
            )
        }
    }

    render() {
        return (
            <>
                <Timeline>
                    {this.ruleList.map((i, index) => {
                        return (
                            <TimelineItem
                                v-slots={{
                                    dot: () => {
                                        return (
                                            <div class="text-blue-default font-bold after:content-['或'] after:block">
                                                {numberToLetter(index + 1)}
                                            </div>
                                        )
                                    },
                                    default: () => {
                                        return <div class="flex">{this.renderRule(i, index)}</div>
                                    }
                                }}
                            ></TimelineItem>
                        )
                    })}
                    {this.ruleList.length !== this.options.length && (
                        <TimelineItem
                            v-slots={{
                                dot: () => {
                                    return <div class="text-blue-default font-bold">B</div>
                                },
                                default: () => {
                                    return (
                                        <Button icon={h(PlusOutlined)} onClick={this.onAddRule}>
                                            添加条件
                                        </Button>
                                    )
                                }
                            }}
                        ></TimelineItem>
                    )}
                </Timeline>
            </>
        )
    }
}

export default toNative<{}, {}>(ValidRule)
